#!/bin/bash
# Copyright (C) 2019 Checkmk GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

# Reason for this no-op: shellcheck disable=... before the first command disables the error for the
# entire script.
:

# Disable unused variable error (needed to keep track of version)
# shellcheck disable=SC2034
CMK_VERSION="2.5.0b1"

_socket_exists() {
    [ -S "/omd/sites/${1}/tmp/run/live" ]
}

_query_site() {
    site_cmd() {
        # DO NOT ACCESS /omd/sites/${site}/bin/cmd directly.
        # bin might point anywhere -> priv escalation.
        printf "/omd/versions/%s/bin/%s" "$(realpath "/omd/sites/${1}/version" | sed 's|.*/||')" "${2}"
    }

    site_lib() {
        printf "/omd/versions/%s/lib" "$(realpath "/omd/sites/${1}/version" | sed 's|.*/||')"
    }
    echo -e "${2}" | LD_LIBRARY_PATH="$(site_lib "${1}"):${LD_LIBRARY_PATH}" waitmax 3 "$(site_cmd "${1}" unixcat)" "/omd/sites/${1}/tmp/run/live"
}

#   .--queries-------------------------------------------------------------.
#   |                                        _                             |
#   |                   __ _ _   _  ___ _ __(_) ___  ___                   |
#   |                  / _` | | | |/ _ \ '__| |/ _ \/ __|                  |
#   |                 | (_| | |_| |  __/ |  | |  __/\__ \                  |
#   |                  \__, |\__,_|\___|_|  |_|\___||___/                  |
#   |                     |_|                                              |
#   '----------------------------------------------------------------------'

get_tag_stats() {
    local site header tags_arr tags_query
    site="${1}"
    header="${2}"
    IFS=" " read -r -a tags_arr <<<"${header}"

    { [ "${#tags_arr[@]}" -ne 0 ] && _socket_exists "${site}"; } || return

    tags_query="GET hosts\n"
    for tag in "${tags_arr[@]}"; do
        tags_query="${tags_query}Stats: custom_variables ~ TAGS ${tag}\n"
    done
    echo "Tags|${header}|$(_query_site "${site}" "${tags_query}")"
}

get_check_command_stats() {
    local site srv_commands commands_query
    site="${1}"
    srv_commands="${2}"

    { [ -n "${srv_commands}" ] && _socket_exists "${site}"; } || return

    commands_query="GET services\n"
    for srv_cmd in ${srv_commands}; do
        commands_query="${commands_query}Stats: check_command ~~ ${srv_cmd}$\n"
    done
    echo "Service check commands|${srv_commands}|$(_query_site "${site}" "${commands_query}")"
}

#.
#   .--main----------------------------------------------------------------.
#   |                                       _                              |
#   |                       _ __ ___   __ _(_)_ __                         |
#   |                      | '_ ` _ \ / _` | | '_ \                        |
#   |                      | | | | | | (_| | | | | |                       |
#   |                      |_| |_| |_|\__,_|_|_| |_|                       |
#   |                                                                      |
#   '----------------------------------------------------------------------'

_read_config() {
    SITES=
    TAGS=
    SERVICE_CHECK_COMMANDS=
    # shellcheck source=../cfg_examples/site_object_counts.cfg
    [ -e "${MK_CONFDIR}/site_object_counts.cfg" ] && . "${MK_CONFDIR}/site_object_counts.cfg"
}

main() {
    _read_config

    if type omd >/dev/null; then
        echo "<<<site_object_counts:sep(124)>>>"
        if [ -n "$SITES" ]; then
            read -r -a sites <<<"${SITES}"
        else
            read -r -a sites <<<"$(omd sites | cut -d' ' -f1 | paste -s)"
        fi

        if [ -n "$TAGS" ]; then
            tags="$TAGS"
        fi

        if [ -n "$SERVICE_CHECK_COMMANDS" ]; then
            service_check_commands="$SERVICE_CHECK_COMMANDS"
        fi

        for site in "${sites[@]}"; do
            site_tags="TAGS_$site"
            site_tags=${!site_tags}
            if [ -n "$tags" ] && [ -n "$site_tags" ]; then
                site_tags="$tags $site_tags"
            elif [ -n "$tags" ]; then
                site_tags="$tags"
            fi

            site_service_check_commands="SERVICE_CHECK_COMMANDS_$site"
            site_service_check_commands=${!site_service_check_commands}
            if [ -n "$service_check_commands" ] && [ -n "$site_service_check_commands" ]; then
                site_service_check_commands="$service_check_commands $site_service_check_commands"
            elif [ -n "$service_check_commands" ]; then
                site_service_check_commands="$service_check_commands"
            fi

            echo "[[[$site]]]"
            get_tag_stats "$site" "$site_tags"
            get_check_command_stats "$site" "$site_service_check_commands"
        done
    fi
}

[ -z "${MK_SOURCE_PLUGIN}" ] && main
